<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small">
        <el-table-column align="center" label='编号' width="50" prop="id"></el-table-column>
        <el-table-column align="center" label='姓名' prop="nick"></el-table-column>
        <el-table-column align="center" label="用户名" prop="name"></el-table-column>
        <el-table-column align="center" label="手机" prop="phone"></el-table-column>
        <el-table-column align="center" label="性别" prop="sex">
          <template slot-scope="scope">
            {{scope.row.sex==1?'男':scope.row.sex==2?'女':scope.row.sex==3?'保密':'未设置'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限组" prop="group_name"></el-table-column>
        <el-table-column align="center" label="创建日期" prop="registration"></el-table-column>
        <el-table-column align="center" label="最后登录" prop="lastlogin"></el-table-column>
        <el-table-column align="center" label="操作" width="80">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="addEditClick(scope.row.id,scope.$index)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 用户信息弹框 -->
    <el-dialog :close-on-click-modal="false" width="360px" :title="dialogTitle" :visible.sync="addEditDialog"
      @close="callOf('saveForm')">
      <el-form :inline="true" :model="saveForm" ref="saveForm" :rules="rules" size="small">
        <div v-if="!editPassword">
          <el-form-item label="　　姓名" prop="nick">
            <el-input disabled v-model="saveForm.nick" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="　用户名" prop="name">
            <el-input disabled v-model="saveForm.name" class="w200"></el-input>
          </el-form-item>
          <el-form-item label=". 　　性别">
            <el-select placeholder="选择性别" v-model="saveForm.sex">
              <el-option v-for="item in sex" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input type="number" onmousewheel="return false;" v-model="saveForm.phone" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="　　密码" prop="password">
            <el-input disabled type="password" v-model="saveForm.password" class="w200"></el-input>
          </el-form-item>
          <div style="text-align:center">
            <el-button type="text" @click="editPassClick()" size="small">需要修改密码吗?</el-button>
          </div>
        </div>
        <div v-if="editPassword">
          <el-form-item label="　原密码" prop="old_pwd">
            <el-input type="password" v-model="saveForm.old_pwd" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="　新密码" prop="new_pwd">
            <el-input type="password" v-model="saveForm.new_pwd" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="new_pwd2">
            <el-input type="password" v-model="saveForm.new_pwd2" class="w200"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveClick('saveForm')" size="small">保 存</el-button>
        &nbsp;
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getList,
    getPage,
    edit_self,
    save,
    // getUser,
  } from "@/api/setting/user_info";
  import md5 from 'js-md5';
  import { isvalidUsername, isvalidPassword, mobile } from '@/utils/validate';
  import { JSEncrypt } from 'jsencrypt';
  export default {
    data() {
      const validateUserName = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('2-25位 字母+数字,不包含特殊字符!'))
        } else {
          callback()
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (!isvalidPassword(value)) {
          callback(new Error('长度6-12位字符，不能纯数字或字母!'))
        } else {
          callback()
        }
      };
      const validateMobile = (rule, value, callback) => {
        if (!mobile(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      };
      return {
        public_key: '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3//sR2tXw0wrC2DySx8vNGlqt3Y7ldU9+LBLI6e1KS5lfc5jlTGF7KBTSkCHBM3ouEHWqp1ZJ85iJe59aF5gIB2klBd6h4wrbbHA2XE1sq21ykja/Gqx7/IRia3zQfxGv/qEkyGOx+XALVoOlZqDwh76o2n1vP1D+tD3amHsK7QIDAQAB-----END PUBLIC KEY-----',
        sex: [{ id: '0', name: '未设置' }, { id: '1', name: '男' }, { id: '2', name: '女' }, { id: '3', name: '保密' }],
        dialogTitle: '编辑用户信息',
        url: '',
        addEditDialog: false,
        houseDialog: false,
        list: null,
        listLoading: false,
        editPassword: false,
        currentPage: 1,
        totalDataNumber: 0,
        formInline: {
          nick: ''
        },
        houseList: [],
        haveHouseList: [],
        addHouseForm: {
          house_id: '',
          clerk_id: '',
          clerk_house_id: 0
        },
        saveForm: {

        },
        rules: {
          nick: [
            { required: true, trigger: 'blur', message: '请输入姓名' },
          ],
          name: [
            { required: true, trigger: 'blur', validator: validateUserName },
          ],
          phone: [
            { required: true, trigger: 'blur', validator: validateMobile },
          ],
          password: [
            { required: true, trigger: 'blur', validator: validatePassword }
          ],
          old_pwd: [
            { required: true, trigger: 'blur', validator: validatePassword }
          ],
          new_pwd: [
            { required: true, trigger: 'blur', validator: validatePassword }
          ],
          new_pwd2: [
            { required: true, trigger: 'blur', validator: validatePassword }
          ],
        },
      };
    },
    beforeRouteEnter(to, from, next) {
      next((vm) => {//当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
        if (!vm.list) {
          vm.fetchData();
        }
      })
    },
    methods: {
      // 需要修改密码
      editPassClick() {
        this.editPassword = true
      },
      // 保存按钮
      saveClick(formName) {
        // console.log(1,this.saveForm) 
        let data;
        let encryptor = new JSEncrypt()
        encryptor.setPublicKey(this.public_key)
        this.url = this.editPassword ? '/User/change_pwd' : '/User/edit_self'
        if (this.editPassword) {
          if (this.saveForm.new_pwd != this.saveForm.new_pwd2) {
            this.$message({ type: 'error', message: '两次密码不一致，请重新输入密码!' })
            this.saveForm.password = ''
            this.saveForm.password2 = ''
            return;
          }
          data = {
            id: this.saveForm.id,
            old_pwd: encryptor.encrypt(md5(this.saveForm.old_pwd)),
            old_pwd_len: this.saveForm.old_pwd.length,
            new_pwd: encryptor.encrypt(md5(this.saveForm.new_pwd)),
            new_pwd_len: this.saveForm.new_pwd.length,
          }
        } else {
          data = {
            id: this.saveForm.id,
            sex: this.saveForm.sex,
            mobile: this.saveForm.phone,
          }
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            save(data, this.url).then(response => {
              this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message })
              if (response.code == 1) {
                this.fetchData();
                this.addEditDialog = false;
              }
            })
          }
        })
      },
      // 添加编辑用户按钮
      addEditClick(id, index) {
        this.addEditDialog = true;
      },
      // 列表获取
      fetchData() {
        this.listLoading = true;
        this.list = [];
        getList({}).then(response => {
          this.list.push(response);
          this.saveForm = response
          this.saveForm.password = '123456..'
          // this.saveForm.old_pwd = ''
          // this.saveForm.new_pwd = ''
          // this.saveForm.new_pwd2 = ''
          this.listLoading = false;
        }).catch(res=>{
            this.listLoading=false;
        })
      },
      //关闭弹框重置
      callOf(formName) {
        this.$refs[formName].resetFields();
        this.editPassword = false;
        this.saveForm.old_pwd = ''
        this.saveForm.new_pwd = ''
        this.saveForm.new_pwd2 = ''
      },
    }
  };
</script>